<?php
namespace backend\controllers;

use backend\controllers\RbacController;
use backend\models\TmeOrderinfo;
use backend\models\TmeOrderdetailsinfo;
use yii\base\Exception;
use backend\models\OrderForm;
use frontend\models\TbaMemberinfo;
use backend\models\TbaDeliveryinfo;
use yii\log\DbTarget;
use backend\models\TmeMerchandiseavg;



/**
 * #name=订单管理#
 * 
 *
 */

class OrderController extends RbacController {
	
	public  $layout = 'ace';   //定义布局
	public $enableCsrfValidation = false;
	
	
	/**
	 * #operation=订单列表#
	 */
	public  function  actionIndex(){
		
					
		return  $this->render('index');
	}
	
	
	/**
	 * #operation=订单列表数据源#
	 */
	public function actionDatasource(){
				
		return $this->renderPartial('datasource');
	}
	
	
	/**
	 * #operation=订单详情#
	 * @return string
	 */
	public function actionView(){
		
		$model = new OrderForm(['scenario'=>'view']);
				
		if(\yii::$app->request->post('action') == "see"){
		
			$id = \yii::$app->request->post('alterid');        //表单数据的ID
			$order = TmeOrderinfo::find()->where(['ID'=>$id])->asArray()->one();      //查询订单表
			$state = $order['BillStatus'];					   //订单状态码
			$uid = $order['Uid'];                              //会员表ID
		
			//判断订单状态
			if($state == 0 )
				$states = "待审核";
			if($state == 1 )
				$states = "待发货";
			if($state == 2 )
				$states = "已发货";
			if($state == 3 )
				$states = "已收货";
		
			//会员信息
			$members = TbaMemberinfo::find()->where(['ID'=>$uid])->asArray()->one();  //查询会员表
			$mail = $members['Email'];    	    			   //会员邮箱
			$member = $order['UserName'];   				   //会员名
			$recMan = $order['RecMan'];   					   //收货人
			$post = $order['PostCode'];       				   //邮编
			$phone = $order['LinkTel'];       				   //联系人电话
			$address = $order['RecAddress'];  				   //联系人地址
			$delivery = $order['DeliveryName'];                //配送方式
		
			//查询订单详情表，提取商品信息
			$orderInfo = TmeOrderdetailsinfo::find()->where(['BillCode'=>$order['BillCode']])->asArray()->all();  //查询订单详情表
			
		}
					
		return $this->renderPartial('view',['model'=>$model,'orderInfo'=>$orderInfo,
											'member'=>$member,
											'mail'=>$mail,
											'states'=>$states,
											'recMan'=>$recMan,
											'post'=>$post,
											'phone'=>$phone,
											'address'=>$address,
											'delivery'=>$delivery,
											
											]);
		
	}
	
		
	/**
	 * #operation=订单修改#
	 */
	public function actionAlter(){
		
		//判断是否是展现修改界面的动作
		if(\yii::$app->request->post('alterid') && \yii::$app->request->post('action') == "view" ){
		
			$id = \yii::$app->request->post('alterid');       //表单数据的ID
			$orders = TmeOrderinfo::findOne(['ID'=>$id ]);    //查询订单表
			$mail = $orders->u['Email'];       	              //会员邮箱
			$orders = TmeOrderinfo::find()->where(['ID'=>$id])->asArray()->one();
			$devId =$orders['TBa_ID'];
			$billCode = $orders['BillCode'];        		  //订单号
			$member = $orders['UserName'];     	    		  //会员名
			$state = $orders['BillStatus'];         		  //订单状态
			$getperson = $orders['RecMan'];         		  //收货人
			$post = $orders['PostCode'];            		  //邮编
			$phone = $orders['LinkTel'];           			  //联系人电话
			$address = $orders['RecAddress'];       		  //联系人地址
			$delivery = $orders['DeliveryName'];    		  //物流
		
			//查询订单详情表，提取商品信息
			$orderInfo = TmeOrderdetailsinfo::find()->where(['BillCode'=>$billCode])->asArray()->all();  //查询订单详情表
			
			//判断订单状态
			if($state == 0 )
				$states = "待审核";
			if($state == 1 )
				$states = "待发货";
			if($state == 2 )
				$states = "已发货";
			if($state == 3 )
				$states = "已收货";
		
			$deliverys = TbaDeliveryinfo::find()->where(['State'=>1])->asArray()->all();       //查询所有的物流配送商
		
		}
		
		
		//表单验证：如果进行了修改的动作,进行数据处理
		if(\yii::$app->request->post('action') =="alter"){
		
			$model = new OrderForm(['scenario'=>'alter']);				  			  //实例化订单表单模型
			$orderForm = \yii::$app->request->post('OrderForm');		  			   
			$model->recMan = $orderForm['recMan'];  					  			  //收货人
			$model->post = $orderForm['post'];							  			  //邮编
			$model->tel = $orderForm['tel'];							  			  //手机号码
			$model->address = $orderForm['address'];					  			  //收货地址
			

			//表单验证
		    if($model->validate(['recMan','post','tel','address'])){
			
			 $orderForm = \yii::$app->request->post('OrderForm');
			 $id = \yii::$app->request->post('alterid');            	 			  //需要修改的ID
			 $deliveryId = \yii::$app->request->post('delivery');  	      			  //修改后的物流配送方式
			 $delivery = TbaDeliveryinfo::findOne(['ID'=>$deliveryId]);   			  //查询物流商配送表
			 $delivery = $delivery['DeliveryName'];                       			  //修改后的物流名
				 	
			 //在订单表里更新修改的数据，为需要更新的字段赋值
			 $order = TmeOrderinfo::findOne(['ID'=>$id]);                 			  //查询订单表
			 $order->RecMan =$orderForm['recMan'];						  			  //更新收货人
			 $order->LinkTel = $orderForm['tel'];						  			  //更新联系电话
			 $order->RecAddress = $orderForm['address'];				  			  //更新收货地址
			 $order->PostCode = $orderForm['post'];						  			  //更新邮编
			 $order->TBa_ID =$deliveryId;      					 		  			  //物流ID
			 $order->DeliveryName =$delivery;   						  			  //物流名
				
			 //判断是否有商品数据的提交
			 if(isset($orderForm['num'])  && isset($orderForm['price']) ){
			 	
			 	$num = $orderForm['num'];											 //数量
			 	$price = $orderForm['price'];										 //价格
			 	$connect = \yii::$app->db;   										 //建立数据库连接
			 	$transaction = $connect->beginTransaction();        				 //开启事务
			 	try {	
			 				 		
			 		foreach ($price as $k=>$n ){			 		
			 			$model->num = $num[$k]; 						         	 //商品数量
			 			$model->price = $n; 					                	 //商品单价
			 		
			 			//表单验证
			 			if($model->validate(['num','price'])){
			 				$number = $num[$k];         				             //修改后的商品数量
			 				$price = $n;        							         //修改后的单价
			 				$orderInfo = TmeOrderdetailsinfo::findOne(['ID'=>$k]);   //查询订单详情表
			 				$orderInfo->Num = $number;    							 //数量
			 				$orderInfo->Price = $price;   							 //价格
			 				$totalPrice = $number * $price;                     	 //商品总价
			 				if(!$orderInfo->save())
			 					throw  new Exception("数据插入失败", 1);
			 				 
			 			}else{
			 		
			 				$errors = $model->errors;   //错误信息
			 				$temp ="";
			 				foreach ($errors as $v) {
			 					foreach ($v as $p ){
			 						$temp .= $p."，";
			 					}
			 				}
			 				exit("<script>alert('".$temp."');window.history.go(-1);</script>");  //返回错误信息
			 			}
			 		}
			 		
			 		$orderInfo = TmeOrderdetailsinfo::find()->where(['BillCode'=>$order['BillCode']])->asArray()->all();   //查询订单详情表
			 		$total = 0;
			 		foreach ($orderInfo as $v ){
			 			$money =$v['Num']*$v['Price'];
			 			$total += $money;
			 		
			 		}
			 			
			 		$order->TotalMoney =$total;      					  //修改总价
			 		if($order->save())
			 			$transaction->commit();                    	   	  //事务提交
			 		
			 		exit("<script>alert(\"修改成功rrr\");window.history.go(-1);</script>");
			 		
			 	} catch (Exception $e) {
			 		
			 		$transaction->rollBack();                      		 //事物回滚
			 		exit("<script>alert(\"修改失败\");window.history.go(-1);</script>");			 		
			 	} 			
			 } 
			  
			 	
			 if($order->save())			 	
			 	exit("<script>alert(\"修改成功\");window.history.go(-1);</script>");
			 else			 	
			 	exit("<script>alert(\"修改失败\");window.history.go(-1);</script>");		
			} else{
				
				$errors = $model->errors;   //错误信息
				$temp ="";
				foreach ($errors as $v) {
					foreach ($v as $p ){
						$temp .= $p."，";
					}				
				}
				exit("<script>alert('".$temp."');window.history.go(-1);</script>");   //返回错误信息
			}
		}
		
		
		$model = new OrderForm(['scenario'=>'alter']);    							 //实例化订单表单模型
		return $this->renderPartial('alters',['model'=>$model,'orderInfo'=>$orderInfo,
												'oid'=>$id,
												'member'=>$member,
												'mail'=>$mail,
												'states'=>$states,
												'state'=>$state,
												'devId'=>$devId,
												'deliverys'=>$deliverys,
												'getperson'=>$getperson,
												'post'=>$post,
												'phone'=>$phone,
												'address'=>$address,
												'delivery'=>$delivery,
																								
											 ]);
		
	}
	
	
	/**
	 * #operation=订单删除#
	 */
	public function actionDelet(){
		
			//判断是否是删除动作
			if(\yii::$app->request->post("action") == "delet"){			
				$id = \yii::$app->request->post('orderid');  		//订单ID
				$order = TmeOrderinfo::find()->where(['ID'=>$id])->asArray()->one();
				$BillCode = $order['BillCode'];             		//订单号
				$order = TmeOrderinfo::findOne(['ID'=>$id]);        //订单表
				
				if(TmeOrderdetailsinfo::findOne(['BillCode'=>$BillCode]) !== null){
					$ordreinfo = TmeOrderdetailsinfo::findOne(['BillCode'=>$BillCode]);   //查询订单详情表
					$connect = \yii::$app->db;   					//建立数据库连接
					$transaction = $connect->beginTransaction();    //开启事务	
					try {
						if(!$ordreinfo->deleteAll(['BillCode'=>$BillCode]))
							throw new Exception("数据删除失败",1);
						if(!$order->delete())
							throw new Exception("数据删除失败",1);
						$transaction->commit();                    	 //事务提交
					   
					} catch (Exception $e) {
						$transaction->rollBack();                    //事物回滚
						//exit('删除失败');							
					}	
								
			    }else{
			    	echo json_encode('删除失败');
					exit;
				}
		
		  }
		
		//判断是否是全部删除	
		if(\yii::$app->request->post("action") == "deletall"){
			
			if(\yii::$app->request->post('check')){
				$check = \yii::$app->request->post('check');
				foreach ($check as $v ){
					$order = TmeOrderinfo::findOne(['ID'=>$v]);     //查询订单表									
				  if( TmeOrderdetailsinfo::findOne(['BillCode'=>$order['BillCode']]) !== null ){      
				  	$ordreinfo = TmeOrderdetailsinfo::findOne(['BillCode'=>$order['BillCode']]);   //查询订单详情表
				  	
				  	$connect = \yii::$app->db;   					//建立数据库连接
					$transaction = $connect->beginTransaction();    //开启事务
					try {
						if(!$ordreinfo->deleteAll(['BillCode'=>$order['BillCode']]))
							throw new Exception("数据删除失败",1);
						if(!$order->delete())
							throw new Exception("数据删除失败",1);
						$transaction->commit();                    	 //事务提交
						
					} catch (Exception $e) {
						
						$transaction->rollBack();                    //事物回滚
						exit("<script>alert('删除失败');window.history.go(-1);</script>");
					}
				  }else{
				  	exit("<script>alert('删除失败');window.history.go(-1);</script>");
				  }		
			 }
			 exit("<script>window.history.go(-1);myTable.draw( false );</script>");
				
			}else{
				exit("<script>alert('请选择后在删除');window.history.go(-1);</script>");
			}						
		}			
	}

	
	 /**
	 * #operation=订单审核#
	 */ 
	 public function actionExamine(){
	 	
	 	if(\yii::$app->request->isPost && \yii::$app->request->post('action') == 'examine' ){
	 		
	 		$id = \yii::$app->request->post('id');   		 //订单ID
	 		$order = TmeOrderinfo::findOne(['ID'=>$id]);     //  查询订单表
	 		$orderinfo = $order->tmeOrderdetailsinfos;	     //查询订单详情表，为一个数组	 		
	 		$temp = [];
	 		foreach ($orderinfo as $v){
	 			$temp[$v['TMe_ID']] = $v['Num'];	 		 //构建自定义数组 		
	 		}
	 		$error = [];
	 		$connect = \yii::$app->db;   					//建立数据库连接
	 		$transaction = $connect->beginTransaction();    //开启事务
	 		try {
	 			
	 			//进行订单审核
	 			foreach ($temp as $k=>$v){
	 				$merchandiseavg = TmeMerchandiseavg::findOne(['TMe_ID'=>$k]);    //查询库存表
	 				$number = $merchandiseavg['Number'];   							 //商品库存数量
	 				$name = $merchandiseavg->tMe['MerchandiseName'];   				 //商品名
	 				if($number < $v ){
	 					$error[] =$name.'商品数量超出库存数量，请重新修改该商品的订单数量';
	 				}else{
	 					$merchandiseavg->Number = $number - $v;   					 //修改商品数量
	 					if(!$merchandiseavg->save())
	 						$error[] =$name.'商品数量修改失败';
	 				}
	 			}
	 			
	 			if(empty($error)){	 				
	 				$order->BillStatus = '2';										//修改订单状态
	 				if($order->save()){		 					
	 					$transaction->commit();                    	 				//事务提交
	 					echo json_encode('审核通过');
	 					exit;
	 				}else{
	 					echo json_encode('审核未通过');
	 					exit;
	 				} 
	 								
	 			}else{
	 				$errors = json_encode($error);
	 				throw new Exception($errors,1);	 				
	 			}	 			
	 			
	 		}catch (Exception $e) {	 			
	 			$transaction->rollBack();                    					  //事物回滚	 			
	 			echo $e->getMessage();
	 			exit;
	 		}			 			 		
	 	} 	
	 }
	
	
	
}

?>

